// app/model/user_organization_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, ENUM, TEXT } = app.Sequelize;

  const UserOrganization = app.model.define('user_organization', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    userId: {
      type: INTEGER,
      allowNull: false,
      field: 'user_id',
      comment: '用户ID'
    },
    organizationId: {
      type: INTEGER,
      allowNull: false,
      field: 'organization_id',
      comment: '组织ID'
    },
    role: {
      type: STRING(50),
      comment: '在组织中的角色'
    },
    permissions: {
      type: TEXT,
      comment: '特殊权限'
    },
    status: {
      type: ENUM('active', 'inactive'),
      defaultValue: 'active',
      comment: '状态'
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'user_organizations',
    timestamps: true,
    underscored: true
  });

  // 添加关联关系
  UserOrganization.associate = function() {
    // 用户组织与组织的关联
    if (app.model.OrganizationModel) {
      UserOrganization.belongsTo(app.model.OrganizationModel, {
        foreignKey: 'organizationId',
        as: 'organization'
      });
    }
    
    // 用户组织与用户的关联
    if (app.model.UserModel) {
      UserOrganization.belongsTo(app.model.UserModel, {
        foreignKey: 'userId',
        as: 'user'
      });
    }
  };

  return UserOrganization;
};